package com.example.order.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

public class JsonUtils {
    static ObjectMapper mapper = new ObjectMapper();

    /**
     * 对象转json
     * @param obj
     * @return
     */
    public static String toJson(Object obj){
        try {
            return mapper.writeValueAsString(obj );
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * String 转对象
     * @param
     * @return
     */
    public static Object toObject(String str, Class classType){
            try {
                return mapper.readValue(str,classType);
            } catch (IOException e) {
                e.printStackTrace();
            }
        return null;
    }
    /**
     * String 转复杂对象
     * @param
     * @return
     */
    public static Object toObject(String str, TypeReference classType){
        try {
            return mapper.readValue(str,classType);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


}
